<template>
  <div>
    <a-button size="large" class="editable-add-btn" @click="addVisible = true">
      <a-icon type="plus"/>
      添加操作员
    </a-button>
    <a-input-search
        v-model="keyword"
        placeholder="请输入用户名"
        enter-button="搜索用户"
        style="width: 400px;margin-left: 20px"
        size="large"
        @search="onSearch"
    />
    <a-button style="margin-left: 10px" size="large" type="danger" @click="reset">
      重置
    </a-button>
    <a-table :columns="columns" :data-source="admins" rowKey="id" :loading="loading">
      <a slot="email" slot-scope="email">{{ email }}</a>
      <span slot="customTitle"><a-icon type="smile-o"/> 邮箱</span>
      <span slot="enable" slot-scope="enable">
        <a-tag :color="enable === 0 ? 'green' : 'cyan'">{{ enable === 0 ? '可用' : '锁定' }}</a-tag>
      </span>
      <span slot="action" slot-scope="text, record, index">
        <a-dropdown>
          <a class="ant-dropdown-link" @click="e => e.preventDefault()">操作 <a-icon type="down"/></a>
          <a-menu slot="overlay">
<!--            <a-menu-item>-->
<!--              <a-button type="link" @click="updateEmail(index)"><a-icon type="mail"/> 邮箱修改</a-button>-->
<!--            </a-menu-item>-->
<!--            <a-menu-item>-->
<!--              <a-button type="link" @click="updatePassword(index)"><a-icon type="lock"/> 密码修改</a-button>-->
<!--            </a-menu-item>-->
            <a-menu-item>
              <a-button type="link" @click="initPassword(index)"><a-icon type="lock"/> 重置密码</a-button>
            </a-menu-item>
            <a-menu-item>
              <a-button type="link" @click="updateRoles(index)"><a-icon type="gateway"/> 权限修改</a-button>
            </a-menu-item>
            <a-menu-item>
              <a-button type="link" @click="updateEnable(index)"><a-icon type="scissor"/> 锁定解绑</a-button>
            </a-menu-item>
            <a-menu-item>
              <a-button type="link" @click="removeAdmin(index, record.id)"><a-icon type="delete"/> 删除</a-button>
            </a-menu-item>
          </a-menu>
        </a-dropdown>
      </span>
    </a-table>

    <a-modal
        title="添加操作员"
        :visible="addVisible"
        :confirmLoading="addLoading"
        cancelText="返回"
        okText="确认"
        @ok="addSubmit"
        @cancel="addCancel"
    >
      <a-form-model ref="addForm" :model="addForm" :rules="addRules">
        <a-form-model-item label="邮箱" prop="email">
          <a-input placeholder="请输入邮箱" v-model="addForm.email"/>
        </a-form-model-item>
        <a-form-model-item label="用户名" prop="username">
          <a-input placeholder="请输入用户名" v-model="addForm.username"/>
        </a-form-model-item>
      </a-form-model>
    </a-modal>

    <a-modal
        title="密码修改"
        :visible="passwordVisible"
        :confirmLoading="passwordLoading"
        cancelText="返回"
        okText="确认"
        @ok="passwordSubmit"
        @cancel="passwordCancel"
    >
      <a-form-model ref="passwordForm" :model="passwordForm" :rules="passwordRules">
        <a-form-model-item label="旧密码" prop="oldPass">
          <a-input-password placeholder="请输入旧密码" v-model="passwordForm.oldPass" />
        </a-form-model-item>
        <a-form-model-item label="新密码" prop="newPass">
          <a-input-password placeholder="请输入新密码" v-model="passwordForm.newPass" />
        </a-form-model-item>
        <a-form-model-item label="确认新密码" prop="checkPass">
          <a-input-password placeholder="请输入新密码" v-model="passwordForm.checkPass" />
        </a-form-model-item>
      </a-form-model>
    </a-modal>

    <a-modal
        title="邮箱修改"
        :visible="emailVisible"
        :confirmLoading="emailLoading"
        cancelText="返回"
        okText="确认"
        @ok="emailSubmit"
        @cancel="emailCancel"
    >
      <a-form-model ref="emailForm" :model="emailForm" :rules="emailRules">
        <a-form-model-item label="绑定邮箱" prop="email">
          <a-input placeholder="请输入邮箱" v-model="emailForm.email"/>
        </a-form-model-item>
      </a-form-model>
    </a-modal>

    <a-modal
        title="权限修改"
        width="500px"
        :visible="rolesVisible"
        :confirmLoading="rolesLoading"
        cancelText="返回"
        okText="确认"
        @ok="rolesSubmit"
        @cancel="rolesCancel"
    >
      <a-select
          v-model="selectRoles"
          mode="multiple"
          style="width: 100%"
          placeholder="请选择角色"
          option-label-prop="label"
      >
        <a-select-option :value="item.id"
                         :label="item.name"
                         v-for="(item ,index) in roles"
                         :key="index">
          <span role="img" :aria-label="item.name"></span>{{ item.name + ' (描述: ' + item.description + ')' }}
        </a-select-option>
      </a-select>
    </a-modal>

  </div>
</template>
<script>
const columns = [
  {
    dataIndex: 'email',
    key: 'email',
    slots: {title: 'customTitle'},
    scopedSlots: {customRender: 'email'},
  },
  {
    title: '用户名',
    dataIndex: 'username',
    key: 'username',
  },
  {
    title: '是否可用',
    dataIndex: 'enable',
    key: 'enable',
    scopedSlots: {customRender: 'enable'},
  },
  {
    title: '注册时间',
    key: 'createTime',
    dataIndex: 'createTime',
    scopedSlots: {customRender: 'createTime'},
  },
  {
    title: '更多操作',
    key: 'action',
    scopedSlots: {customRender: 'action'},
  },
];

export default {
  name: 'SysUser',
  data() {
    const validatePass = (rule, value, callback) => {
      if (value === '') {
        callback(new Error('请输入密码'));
      } else {
        if (this.passwordForm.checkPass !== '') {
          this.$refs.passwordForm.validateField('checkPass');
        }
        callback();
      }
    };
    const validatePass2 = (rule, value, callback) => {
      if (value === '') {
        callback(new Error('请再次输入密码'));
      } else if (value !== this.passwordForm.newPass) {
        callback(new Error('两次输入密码不一致!'));
      } else {
        callback();
      }
    };
    return {
      roles: [],
      selectRoles: [],
      admins: [],
      loading: false,
      addVisible: false,
      emailVisible: false,
      passwordVisible: false,
      rolesVisible: false,
      passwordLoading: false,
      emailLoading: false,
      rolesLoading: false,
      addLoading: false,
      columns,
      selectAdmin: {},
      keyword: '',
      passwordForm: {
        oldPass: '',
        newPass: '',
        checkPass: ''
      },
      emailForm: {
        email: ''
      },
      addForm: {
        email: '',
        username: ''
      },
      passwordRules: {
        oldPass: [
          { validator: validatePass, trigger: 'blur' }
        ],
        newPass: [
          { validator: validatePass, trigger: 'blur' }
        ],
        checkPass: [
          { validator: validatePass2, trigger: 'blur' }
        ]
      },
      emailRules: {
        email: [{required: true, message: '请输入邮箱', trigger: 'blur'}]
      },
      addRules: {
        email: [{required: true, message: '请输入邮箱', trigger: 'blur'}],
        username: [{required: true, message: '请输入用户名', trigger: 'blur'}]
      }
    };
  },
  mounted() {
    this.load()
  },
  methods: {
    load() {
      this.loading = true
      this.getRequest('/api/role/').then(resp => {
        if (resp) {
          this.roles = resp
        }
      })
      this.getRequest('/api/admin/?name=' + this.keyword).then(resp => {
        if (resp) {
          if (this.keyword !== '' && resp.length === 0) this.$message.warning('未搜索到相关用户')
          this.admins = resp
          this.loading = false
        }
      })
    },
    passwordSubmit() {
      this.$refs.passwordForm.validate(valid => {
        if (valid) {
          this.passwordLoading = true
          this.passwordForm.adminId = this.selectAdmin.id
          this.putRequest('/admin/pass', this.passwordForm).then(resp => {
            if (resp) {
              this.passwordLoading = false
              this.passwordVisible = false
              this.load()
              this.passwordForm = {
                oldPass: '',
                newPass: '',
                checkPass: ''
              }
            } else {
              this.passwordLoading = false
            }
          })
        }
      })
    },
    passwordCancel() {
      this.$refs.passwordForm.resetFields()
      this.passwordVisible = false
      this.passwordForm = {
        oldPass: '',
        newPass: '',
        checkPass: ''
      }
    },
    emailSubmit() {
      this.$refs.emailForm.validate(valid => {
        if (valid) {
          if (this.checkEmail(this.emailForm.email)) {
            this.emailLoading = true
            this.selectAdmin.email = this.emailForm.email
            this.putRequest('/api/admin/', this.selectAdmin).then(resp => {
              if (resp) {
                this.emailLoading = false
                this.emailVisible = false
                this.load()
                this.emailForm = {
                  email: ''
                }
              } else {
                this.emailLoading = false
              }
            })
          }
        }
      })
    },
    emailCancel() {
      this.$refs.emailForm.resetFields()
      this.emailVisible = false
      this.emailForm = {
        email: ''
      }
    },
    rolesSubmit() {
      let url = '/api/admin/role?aid=' + this.selectAdmin.id
      if (this.selectRoles.length === 0) {
        this.$message.error('未选择角色')
        return false
      }
      this.selectRoles.forEach(rid => {
        url += '&rids=' + rid
      })
      this.rolesLoading = true
      this.putRequest(url).then(resp => {
        if (resp) {
          this.rolesVisible = false
          this.rolesLoading = false
          this.load()
        } else {
          this.rolesVisible = false
          this.rolesLoading = false
          this.load()
        }
      })
      this.selectRoles = []
    },
    rolesCancel() {
      this.rolesVisible = false
      this.selectRoles = []
    },
    addSubmit() {
      this.$refs.addForm.validate(valid => {
        if (valid) {
          if (this.checkEmail(this.addForm.email)) {
            this.addLoading = true
            this.postRequest('/api/admin/', this.addForm).then(resp => {
              if (resp) {
                this.addLoading = false
                this.addVisible = false
                this.load()
                this.addForm = {
                  email: '',
                  username: ''
                }
              } else {
                this.addLoading = false
              }
            })
          }
        }
      })
    },
    addCancel() {
      this.$refs.addForm.resetFields()
      this.addVisible = false
      this.addForm = {
        email: '',
        username: ''
      }
    },
    updateEmail(index) {
      this.selectAdmin = this.admins[index]
      this.emailForm.email = this.selectAdmin.email
      this.emailVisible = true
    },
    updatePassword(index) {
      this.passwordVisible = true
      this.selectAdmin = this.admins[index]
    },
    updateRoles(index) {
      this.rolesVisible = true
      this.selectAdmin = this.admins[index]
    },
    updateEnable(index) {
      this.selectAdmin = this.admins[index]
      if (this.selectAdmin.enable === 0) {
        this.selectAdmin.enable = 1
      } else {
        this.selectAdmin.enable = 0
      }
      this.putRequest('/api/admin/', this.selectAdmin).then(resp => {
        if (resp) {
          this.load()
        } else {
          this.load()
        }
      })
    },
    removeAdmin(index, id) {
      this.selectAdmin = this.admins[index]
      this.$confirm('此操作将永久删除用户' + this.selectAdmin.username + ', 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.deleteRequest('/api/admin/' + id).then(resp => {
          if (resp) {
            this.load()
          }
        })
      }).catch(() => {
        this.$message.info('取消删除')
      });
    },
    initPassword(index) {
      this.selectAdmin = this.admins[index]
      this.$confirm('此操作将重置用户' + this.selectAdmin.username + '的密码，是否继续？', '提示', {
        confirmButtonText: '确认',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.putRequest('/api/admin/init-password?id=' + this.selectAdmin.id).then(resp => {
          if (resp) {
            this.load()
          }
        })
      }).catch(() => {
        this.$message.info('取消操作')
      })
    },
    checkEmail(email) {
      const emailRegex = new RegExp('^\\w{3,}(\\.\\w+)*@[A-z0-9]+(\\.[A-z]{2,5}){1,2}$')
      if (!emailRegex.test(email)) {
        this.$message.error('请输入正确格式的邮箱');
        return false
      } else {
        return true
      }
    },
    onSearch() {
      if (this.keyword === '') {
        this.$message.warning('请输入搜索内容')
      } else {
        this.load()
      }
    },
    reset() {
      this.keyword = ''
      this.load()
    }
  }
};
</script>

<style scoped>
.editable-add-btn {
  margin-bottom: 15px;
}
</style>